//
//  DictRequest.m
//  划词显示
//
//  Created by 盛超 on 2018/8/16.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "DictRequest.h"
#import "MBProgressHUD.h"

@implementation DictRequest

- (CGFloat)requestTimeoutInterval {
    return 60;
}

- (void)requestGetMethodWithSuccess:(void (^)(id))success Failure:(void (^)(NSError *))failure {
    
    //http://172.16.41.235:2048/api/ZXYYTS/W_ZXYYTS_GetCourseware?knowledge=play&levelCode=B
    //1.设置请求路径
    NSString *url = [NSString stringWithFormat:@"%@?DictString=%@",self.requestUrl,_requestParam[@"DictString"]];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//转UTF-8
    NSURL *URL=[NSURL URLWithString:url];
    
    //2.创建请求对象
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];//默认为get请求
    request.timeoutInterval=self.requestTimeoutInterval;//设置请求超时为5秒
    
    //3.发送请求
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        NSLog(@" http response code : %ld",httpResponse.statusCode);
        
        if (error) {
            
            [self showErrorHud:error.code];
            
            failure(error);
            
        } else {
            
            success(data);
        }
    }];
    [dataTask resume];
}

- (void)showErrorHud:(NSInteger)errorcode {
    dispatch_async(dispatch_get_main_queue(), ^{
        
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
        hud.bezelView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
        hud.label.text =[NSString stringWithFormat:@"错误代码:%ld",errorcode];
        hud.label.textColor = [UIColor whiteColor];
        hud.label.font = [UIFont systemFontOfSize:15.0f];
        [hud hideAnimated:YES afterDelay:1.0f];
        
    });
    
}


@end
